<script setup>
import { addRecommendSelfPar } from "@/api/lawyer";
import { onPageScroll } from "@dcloudio/uni-app";
import dayjs from "dayjs";
import { ref, reactive, watch } from "vue";
import { businessOptions } from "@/utils/dict";
import LawyerBusiness from "./components/LawyerBusiness.vue";

/** 业务领域 */
const currentField = ref('');
const activeBusiness = ref([]);
const popupBusinessRef = ref(null);
function handlePopupBusinessOpen(field) {
  currentField.value = field;
  if(businessTag[field]) {
    activeBusiness.value = businessTag[field].split('、');
  }else {
    activeBusiness.value = []
  }
  popupBusinessRef.value.open()
}
function handlePopupBusinessClose() {
  popupBusinessRef.value.close();
}
function handlePopupBusinessConfirm() {
  businessTag[currentField.value] = activeBusiness.value.join('、') || '';
  activeBusiness.value = [];
  popupBusinessRef.value.close();
}
function handleClickBusinessItem(item) {
  if(activeBusiness.value.includes(item)){
    activeBusiness.value.splice(activeBusiness.value.indexOf(item), 1);
  } else {
    activeBusiness.value.push(item);
  }
}
const popupBusinessMoreRef = ref(null);
function handlePopupBusinessMoreOpen() {
  popupBusinessRef.value.close();
  popupBusinessMoreRef.value.open();
}
function handlePopupBusinessMoreClose() {
  popupBusinessMoreRef.value.close();
}

const stepsCurrent = ref(0);
const initFormData = uni.getStorageSync("selfFormData") ? JSON.parse(uni.getStorageSync("selfFormData")) : {
  lawyerFullname: "", // 律师名称
  lawfirmName: "", // 律所名称
  lawyerTelnum: "", // 律师电话
  lawyerEmail: "", // 邮箱
  liveDate: undefined,
  awardApplication: ""
}
/** 表单数据 */
const formData = reactive(initFormData);
watch(formData, (newVal) => {
  uni.setStorage({ key: "selfFormData", data: JSON.stringify(newVal) });
});
const businessTag = reactive({
  zunxian: '',
  shouxuan: '',
  jingxuan: '',
  youxuan: '',
  zixuan: '',
  huixuan: '',
  zhenxuan: ''
})
/** 校验规则 */
const formRules = {
  lawyerFullname: {
    rules: [{ required: true, errorMessage: "请填写您的姓名" }]
  },
  lawfirmName: {
    rules: [{ required: true, errorMessage: "请填写所在律所名称" }]
  },
  lawyerTelnum: {
    rules: [{ required: true, errorMessage: "请填写手机号" }, { format: 'number', errorMessage: '手机号格式错误' }]
  },
  lawyerEmail: {
    rules: [{ required: true, errorMessage: "请填写工作邮箱" }, { format: 'email', errorMessage: '邮箱错误' }]
  },
};

/** uni-forms 组件实例 */
const formRef = ref(null);
const loading = ref(false);

// 上一步 or 返回
function handlePreviousStep() {
  if(stepsCurrent.value == 0) {
    uni.navigateBack()
  } else {
    stepsCurrent.value--
  }
}

// 下一步 or 提交
async function handleNextStep() {
  if(stepsCurrent.value == 1) {
    if (loading.value) return;
    
    formRef.value?.validate &&
    formRef.value.validate(async (err) => {
      // 如果校验成功 ，err 返回 null
      if (err) return false;

      loading.value = true;
      // 调用登陆接口
      // formData.keyClients = JSON.stringify(keyClients.value);
      formData.liveDate = formData.liveDate ? dayjs(formData.liveDate).format('YYYY-MM-DD') : undefined;
      formData.awardApplication = JSON.stringify(businessTag);
      addRecommendSelfPar(formData).then(res=>{
        uni.showToast({title: '提交成功，等待审核...', icon: 'none'});
        uni.removeStorageSync("selfFormData");
        uni.redirectTo({ url: '/pages/user/recommend'});
      }).finally(() => {
        loading.value = false;
      });
    });
  } else {
    // 表单校验
    const res = await formRef.value.validateField(['lawyerFullname', 'lawfirmName', 'lawyerTelnum', 'lawyerEmail']);
    // 如果校验未通过，validateField 会返回错误对象（数组），否则为校验对象
    if (Array.isArray(res)) return;
    stepsCurrent.value++
  }
}

const datetimePickerRef = ref(null)
function handleDatePickerOpen() {
  datetimePickerRef.value.open();
}

function handleDatePickerConfirm(e) {
  formData.liveDate = dayjs(e.value).format('YYYY');
}

// 吸顶变色
const isScrolled = ref(false);
onPageScroll((e)=>{
  isScrolled.value = e.scrollTop > 0;
});
</script>

<template>
  <view class="relative overflow-hidden">
    <page-navbar title="个人申报" :isScrolled="isScrolled"></page-navbar>
    <view class="mx-4 mt-5">
      <image class="w-full align-middle" src="https://static.minglvtang.com/images/steps_1.png" mode="widthFix" />
    </view>
    <view class="mx-4 mt-3 py-3 rounded bg-white">
      <uv-steps :current="stepsCurrent" activeColor="#1373FF" inactiveColor="#999999">
        <uv-steps-item>
          <template v-slot:title>
            <view class="text-(sm #1373FF)">个人信息</view>
          </template>
        </uv-steps-item>
        <uv-steps-item>
          <template v-slot:title>
            <view class="text-sm" :class="stepsCurrent > 0 ? 'text-#1373FF': 'text-#999999'">申报奖项和业务标签</view>
          </template>
        </uv-steps-item>
      </uv-steps>
    </view>

    <uni-forms ref="formRef" label-width="0" :model="formData" :rules="formRules">
      <view class="mx-4 mt-3 bg-white p-3 rounded-lg grid gap-3" v-show="stepsCurrent == 0">
        <uni-forms-item name="lawyerFullname">
          <view class="py-3 flex justify-between items-center border-b-(~ solid #F4F6F7)">
            <view class="text-(sm #333333) font-semibold before:content-['*'] before:text-red-500 before:mr-1">姓名</view>
            <input class="text-(sm right)" v-model="formData.lawyerFullname" placeholder="填写您的姓名" />
          </view>
        </uni-forms-item>
        <uni-forms-item name="lawfirmName">
          <view class="py-3 flex justify-between items-center border-b-(~ solid #F4F6F7)">
            <view class="text-(sm #333333) font-semibold before:content-['*'] before:text-red-500 before:mr-1">所在律所名称</view>
            <input class="text-(sm right)" v-model="formData.lawfirmName" placeholder="填写所在律所名称" />
          </view>
        </uni-forms-item>
        <uni-forms-item name="lawyerTelnum">
          <view class="py-3 flex justify-between items-center border-b-(~ solid #F4F6F7)">
            <view class="text-(sm #333333) font-semibold before:content-['*'] before:text-red-500 before:mr-1">手机号</view>
            <input class="text-(sm right)" v-model="formData.lawyerTelnum" placeholder="填写手机号" />
          </view>
        </uni-forms-item>
        <uni-forms-item name="lawyerEmail">
          <view class="py-3 flex justify-between items-center border-b-(~ solid #F4F6F7)">
            <view class="text-(sm #333333) font-semibold before:content-['*'] before:text-red-500 before:mr-1">工作邮箱</view>
            <input class="text-(sm right)" v-model="formData.lawyerEmail" placeholder="填写工作邮箱" />
          </view>
        </uni-forms-item>
        <uni-forms-item name="liveDate">
          <view class="py-3 flex justify-between items-center border-b-(~ solid #F4F6F7)">
            <view class="text-(sm #333333) font-semibold flex-1">出生年份</view>
            <view class="text-(sm right)"
              :class="{'text-#808080': formData.liveDate == undefined}"
              @click="handleDatePickerOpen()"
            >
            {{formData.liveDate || '选择出生年份' }}
            </view>
            <view class="i-ri-arrow-right-s-line text-#808080"></view>
          </view>
        </uni-forms-item>
      </view>

    
      <template v-if="stepsCurrent == 1">
        <view class="mx-4 mt-3 text-(xs #999999)">请填写您申报的奖项和业务标签（每个奖项下的业务标签只可填写最擅长的一个）</view>
        <uni-forms-item name="awardApplication">
        <view class="mx-4 mt-3 bg-white p-3 rounded-lg">
          <view class="text-(sm #333333) font-semibold">1、高精尖业务</view>
          <view class="text-(xs #999999) mt-1">在遇到重大、疑难复杂、小众、前沿的业务，需要找知名律所的大PAR</view> 
          <LawyerBusiness title="客户尊选律师" :value="businessTag.zunxian" @click="handlePopupBusinessOpen('zunxian')" @clear="businessTag.zunxian = ''" />
        </view>
        <view class="mx-4 mt-3 bg-white p-3 rounded-lg">
          <view class="text-(sm #333333) font-semibold">2、 常规性业务（专业维度）</view>
          <view class="text-(xs #999999) mt-1">需要找性价比高的律师</view> 
          <LawyerBusiness title="客户首选律师——多位知名企业法总推荐的优秀律师" :value="businessTag.shouxuan" @click="handlePopupBusinessOpen('shouxuan')" @clear="businessTag.shouxuan = ''" />
          <LawyerBusiness title="客户精选律师——多位知名企业法务推荐的优秀律师" :value="businessTag.jingxuan" @click="handlePopupBusinessOpen('jingxuan')" @clear="businessTag.jingxuan = ''" />
          <LawyerBusiness title="客户优选律师——40岁以下的青年合伙人" :value="businessTag.youxuan" @click="handlePopupBusinessOpen('youxuan')" @clear="businessTag.youxuan = ''" />
        </view>
        <view class="mx-4 mt-3 bg-white p-3 rounded-lg">
          <view class="text-(sm #333333) font-semibold">3、 咨询式业务（行业维度）</view>
          <view class="text-(xs #999999) mt-1">熟悉所在行业的律师</view> 
          <LawyerBusiness title="客户智选律师" :value="businessTag.zixuan" @click="handlePopupBusinessOpen('zixuan')" @clear="businessTag.zixuan = ''" />
        </view>
        <view class="mx-4 mt-3 bg-white p-3 rounded-lg">
          <view class="text-(sm #333333) font-semibold">4、 属地化业务</view>
          <view class="text-(xs #999999) mt-1">北上广深一线城市以外的当地头部律所的优秀律师</view>
          <LawyerBusiness title="客户慧选律师" :value="businessTag.huixuan" @click="handlePopupBusinessOpen('huixuan')" @clear="businessTag.huixuan = ''" />
        </view>
        <view class="mx-4 mt-3 bg-white p-3 rounded-lg">
          <view class="text-(sm #333333) font-semibold">5、跨国性业务</view>
          <view class="text-(xs #999999) mt-1">为中国企业出海提供服务的优秀律师</view> 
          <LawyerBusiness title="客户臻选律师" :value="businessTag.zhenxuan" @click="handlePopupBusinessOpen('zhenxuan')" @clear="businessTag.zhenxuan = ''" />
        </view>
        </uni-forms-item>
      </template>
    </uni-forms>

    <view class="w-86 fixed bottom-0 mb-[--safe-area-inset-bottom] pb-5 left-50% -translate-x-50% z-10 bg-#F6F8FA">
      <view class="px-1 border-(~ solid #31946F) bg-#31946F/8 flex items-center rounded-lg space-x-2">
        <image class="w-7 -translate-y-2" src="https://static.minglvtang.com/images/icons/shield.png" mode="widthFix" />
        <view class="text-(sm #31946F)">我们竭诚保护您的数据安全，请放心填写</view>
      </view>
      <view class="mt-3 flex space-x-3">
        <view class="w-1/3">
          <uv-button
            size="large"
            text="上一步"
            :custom-style="{
              fontSize: '18px',
              height: '48px',
              borderRadius: '8px',
              borderColor: 'transparent'
            }"
            @click="handlePreviousStep"
          ></uv-button>
        </view>
        <view class="flex-1">
          <uv-button
            type="primary"
            size="large"
            :text="stepsCurrent == 1 ? '提交推荐' : '继续填写'"
            :custom-style="{
              fontSize: '18px',
              backgroundImage: 'linear-gradient(to right, #5199F9, #0164E6)',
              height: '48px',
              borderRadius: '8px',
              borderColor: 'transparent'
            }"
            @click="handleNextStep"
          ></uv-button>
        </view>
      </view>
    </view>
    <view class="h-40"></view>

    <uv-datetime-picker ref="datetimePickerRef" mode="year" :minDate="dayjs('1950-01-01').valueOf()" :maxDate="Date.now()" @confirm="handleDatePickerConfirm" round="12" confirmColor="#1373FF"></uv-datetime-picker>

    <!-- 业务领域 -->
    <uni-popup ref="popupBusinessRef" type="bottom">
      <view class="p-4 bg-white rounded-t-lg">
        <view class="flex items-center justify-between">
          <view class="text-(sm #909193)" @click="handlePopupBusinessClose">取消</view>
          <view class="text-sm">选择领域</view>
          <view class="text-(sm #1373FF)" @click="handlePopupBusinessConfirm">确定</view>
        </view>
        <view class="mt-5 gap-3 ">
          <uni-collapse :border="false" accordion value="合规与监管">
            <uni-collapse-item :title="business.label"
             :border="false" title-border="none" :name="business.label" 
             :thumb="business.icon"
             v-for="business in businessOptions" :key="business.label"
            >
              <template></template>
              <view class="flex flex-wrap gap-2 px-3 pb-3">
                <view 
                  v-for="item in business.children" :key="item"
                  class="rounded px-3 py-2 text-sm/6 relative"
                  :class="[activeBusiness.includes(item) ? 'text-white bg-#1373FF border-(~ solid #1373FF)' : 'bg-white border-(~ solid black/8)']"
                  @click="handleClickBusinessItem(item)"
                >{{item}}</view>
              </view>
            </uni-collapse-item>
          </uni-collapse>
          <view class="text-(sm #207AFC center) mt-3" @click="handlePopupBusinessMoreOpen()">没有你的领域？备注说明</view>
        </view>
      </view>
    </uni-popup>

    <uni-popup ref="popupBusinessMoreRef" type="bottom">
      <view class="p-4 bg-white rounded-t-lg">
        <view class="flex items-center justify-between">
          <view class="text-(sm #909193)" @click="handlePopupBusinessMoreClose">取消</view>
          <view class="text-sm">备注领域</view>
          <view class="text-(sm #1373FF)" @click="handlePopupBusinessMoreClose">确定</view>
        </view>
        <view class="mt-5 bg-#F6F7F9 rounded-lg p-2">
          <textarea class="text-sm w-full h-30" v-model="businessTag[currentField]" placeholder="输入你的领域" />
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<style scoped>
:deep(.uni-forms-item) {
  margin-bottom: 0;
}
:deep(.uni-collapse) {
  gap: 0.75rem;
}
:deep(.uni-collapse-item) {
  border-radius:12px;
  background-color: #F6F7F9;
}
:deep(.uni-collapse-item__wrap) {
  background-color: #F6F7F9;
}
:deep(.uni-collapse-item__title-box) {
  background-color: #F6F7F9;
  font-weight: 500;
}
:deep(.uni-collapse-item__title-text) {
  font-size:18px;
}
</style>

